package com.huaxindata.im.main.chat.Helper;

import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.huaxindata.common.http.ProgressRequestBody;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.main.chat.ConversationManager;
import com.huaxindata.im.main.chat.adapter.ChatAdapter;
import com.huaxindata.im.main.chat.bean.FileMsgResponseBean;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.entity.ChatFileMessageBody;
import com.huaxindata.im.model.entity.ChatImageMessageBody;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatVideoMessageBody;
import com.huaxindata.im.model.entity.ChatVoiceMessageBody;
import com.huaxindata.im.util.DownloadManager;
import com.huaxindata.im.util.FileUtil;

import java.io.File;
import java.io.IOException;

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/6.
 * 用于发送和接收文件类消息的帮助类
 */

public class FileHelper {

    public static final String TAG="FileHelper";

    /**
     * 发送语音消息
     */
    public static void sendVoiceMessage(Context context, File file, ChatAdapter adapter){
        Log.e("lwjing","sendVoiceMessage filepath "+ file.getAbsolutePath());
        if (file.length() > 10<<20) {
            Toast.makeText(context, "文件不能大于10M", Toast.LENGTH_SHORT).show();
            return;
        }
        String sender= UserManager.getClientId();
        String receiver = ConversationManager.getChatObject().getClientId();
        ChatMessage message=new ChatMessage(ChatMessageBody.Type.VOICE,sender, receiver,System.currentTimeMillis());
        message.messageState = ChatMessage.Status.DOING;
        ChatVoiceMessageBody chatVoiceMessageBody=new ChatVoiceMessageBody(file.getAbsolutePath());
        message.messageBody=chatVoiceMessageBody;
        message.read=1;//自己发的消息置为已读
        adapter.addMessage(message);
        //更新ui
        refreshUI(adapter,ChatAdapter.RefreshHandler.REFRESH_UI,0);
        MessageStore.insert(message);//将消息存入数据库
        uploadFileMessage(adapter,message);
    }
    public static void sendImageMessage(Context context, File file, ChatAdapter adapter){
        if (file.length() > 10<<20) {
            Toast.makeText(context, "文件不能大于10M", Toast.LENGTH_SHORT).show();
            return;
        }
        String sender= UserManager.getClientId();
        String receiver = ConversationManager.getChatObject().getClientId();
        ChatMessage message=new ChatMessage(ChatMessageBody.Type.IMAGE,sender, receiver,System.currentTimeMillis());
        message.messageState = ChatMessage.Status.DOING;
        ChatImageMessageBody chatImageMessageBody=new ChatImageMessageBody(file.getAbsolutePath());
        message.messageBody=chatImageMessageBody;
        message.read=1;//自己发的消息置为已读
        adapter.addMessage(message);
        //更新ui
        refreshUI(adapter,ChatAdapter.RefreshHandler.REFRESH_UI,0);
        MessageStore.insert(message);//将消息存入数据库
        uploadFileMessage(adapter,message);
    }
    public static void sendVideoMessage(Context context, File file, ChatAdapter adapter){
        if (file.length() > 50<<20) {
            Toast.makeText(context, "文件不能大于10M", Toast.LENGTH_SHORT).show();
            return;
        }
        String sender= UserManager.getClientId();
        String receiver = ConversationManager.getChatObject().getClientId();
        ChatMessage message=new ChatMessage(ChatMessageBody.Type.VIDEO,sender,receiver,System.currentTimeMillis());
        message.messageState = ChatMessage.Status.DOING;
        ChatVideoMessageBody chatVideoMessageBody=new ChatVideoMessageBody(file.getAbsolutePath());
        message.messageBody=chatVideoMessageBody;
        message.read=1;//自己发的消息置为已读
        Log.e(TAG, "xxx=====开始发送视频消息");
        adapter.addMessage(message);
        //更新ui
        refreshUI(adapter,ChatAdapter.RefreshHandler.REFRESH_UI,0);
        MessageStore.insert(message);//将消息存入数据库
        uploadFileMessage(adapter,message);
    }
    /**
     *
     * 上传文件
     *@author:guokailin
     *time:2017/6/28 14:30
     */
    public static void uploadFileMessage(final ChatAdapter adapter, final ChatMessage message){
        final ChatFileMessageBody chatFileMessageBody= (ChatFileMessageBody) message.getMessageBody();
        final File sendFile;
        sendFile = new File(chatFileMessageBody.getLocalPath());
        final ProgressRequestBody requestBody = new ProgressRequestBody(sendFile, null);
        //MultipartBody.Part 类型封装，有别于RequestBody类型
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", sendFile.getName(), requestBody);
        Call<FileMsgResponseBean> call= RetrofitClient.getHttpApi()
                .uploadMsgFile2(part);
        call.enqueue(new Callback<FileMsgResponseBean>() {
            @Override
            public void onResponse(Call<FileMsgResponseBean> call, Response<FileMsgResponseBean> response) {
                if (response == null || !response.isSuccessful()) {
                    message.messageState = ChatMessage.Status.ERROR;
                    //发送失败时，更新状态至数据库，避免下次重发。
                    MessageStore.updateSendingStatus(message.timestamp,message.sender,ChatMessage.Status.ERROR);
                    Log.e(TAG, "onResponse: xxx===============发送文件消息失败，服务器有抽风了");
                    return;
                }
                FileMsgResponseBean responseBean = response.body();
                if (TextUtils.isEmpty(responseBean.getFileAddress())) {
                    message.messageState = ChatMessage.Status.ERROR;
                    //发送失败时，更新状态至数据库，避免下次重发。
                    MessageStore.insert(message);
                    adapter.notifyDataSetChanged();
                    Log.e(TAG, "onResponse: xxx===============发送文件消息失败，没有返回文件地址");
                } else {
                    chatFileMessageBody.setRemotePath(response.body().getFileAddress());
                    message.message=chatFileMessageBody.matchMessage();
                    Log.e("lwjing", "onResponse: 发送的文件详情:"+message.message);
                    MessageStore.insert(message);
                    ConversationManager.sendMessage(message);
                }
            }

            @Override
            public void onFailure(Call<FileMsgResponseBean> call, Throwable t) {
                t.printStackTrace();
                message.messageState = ChatMessage.Status.ERROR;
                //发送失败时，更新状态至数据库，避免下次重发。
                MessageStore.insert(message);
              //  adapter.notifyDataSetChanged();
                Log.e(TAG, "onFailure: xxx=====================发送文件消息失败");
            }
        });
    }
    public static void downLoadFileMessage(final ChatMessage message, Context context, final ChatAdapter adapter){
        final ChatFileMessageBody fileMessageBody= (ChatFileMessageBody) message.getMessageBody();
        String url=fileMessageBody.getRemotePath();
        if (TextUtils.isEmpty(url)) {
            return;
        }
        final String path = FileUtil.getChatFileCacheDir(context,message.sender);//这里只是一个目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        final File file = new File(dir, fileMessageBody.getFileName());
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e("xxx", "xxx==========下载文件:"+url);
        fileMessageBody.downloadStatus= ChatFileMessageBody.DownloadStatus.DOWNLOADING;//下载中
        message.messageState=ChatMessage.Status.DOING;
        MessageStore.updateSendingStatus(message.timestamp,message.sender,ChatMessage.Status.DOING);
        DownloadManager.getInstance().downloadFile(url, file.getPath(), new DownloadManager.DownloadListener() {
            @Override
            public void onSuccess(String savePath) {
                Log.e("xxx", "xxx=======下载文件成功:" + savePath);
                message.messageState= ChatMessage.Status.SUCCESS;
                fileMessageBody.downloadStatus=ChatFileMessageBody.DownloadStatus.DOWNLOADSUCCESS;
                fileMessageBody.setLocalPath(file.getPath());//下载下来了设置本地路径
                if (message.type==ChatMessageBody.Type.VOICE){
                    ChatVoiceMessageBody chatVoiceMessageBody = (ChatVoiceMessageBody) fileMessageBody;
                    chatVoiceMessageBody.duration=chatVoiceMessageBody.getMediaLength(chatVoiceMessageBody.getLocalPath());
                }
                MessageStore.insert(message);
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onError(String error) {
                message.messageState= ChatMessage.Status.ERROR;
                fileMessageBody.downloadStatus=ChatFileMessageBody.DownloadStatus.DOWNLOADERROR;
                MessageStore.insert(message);
                Log.e("xxx", "xxxx======下载失败:"+error);
                //notify 在图片无法下载的时候，会造成循环请求图片下载问题
//                if (adapter != null) {
//                    adapter.notifyDataSetChanged();
//                }
            }
            @Override
            public void onProgress(int percent) {
            }
        });
    }
    /**
     *
     * 刷新适配器ui
     *@author:guokailin
     *time:2017/6/30 10:03
     */
    private static void refreshUI(ChatAdapter adapter,int what,int args){
        if (what == 0) {
            return;
        }
        Message message;
        if (args == 0) {
            message=Message.obtain(adapter.mHandler,what);
        } else {
            message=Message.obtain(adapter.mHandler,what,args,0);
        }
        adapter.mHandler.sendMessage(message);
    }
}
